package com.joymart.order.service;


import com.joymart.common.abstraction.StatusService;
import com.joymart.common.error.handling.JoymartBusinessException;
import com.joymart.common.system.BusinessConfig;
import com.joymart.common.system.IdGenerator;
import com.joymart.common.utils.DatetimeUtils;
import com.joymart.common.utils.SecurityUtils;
import com.joymart.order.model.Order;
import com.joymart.order.repo.OrderRepository;
import com.joymart.product.model.Product;
import com.joymart.product.repo.ProductRepository;
import com.joymart.user.model.BusinessRole;
import com.joymart.user.model.CachedUser;
import com.joymart.user.service.UserCacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jdbc.core.JdbcAggregateTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Optional;

@Service
public class OrderService extends StatusService<Order, Order.Status> {

    @Autowired
    private IdGenerator idGenerator;

    @Autowired
    private BusinessConfig businessConfig;

    @Autowired
    private UserCacheManager userCacheManager;
    @Autowired
    private JdbcAggregateTemplate jdbcAggregateTemplate;
    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private ProductRepository productRepository;

    public Order getById(String orderId) {
        return jdbcAggregateTemplate.findById(orderId, Order.class);
    }

    public void save(Order order) {
        boolean existed = jdbcAggregateTemplate.existsById(order.getId(), Order.class);
        if (existed) {
            jdbcAggregateTemplate.save(order);
        } else {
            jdbcAggregateTemplate.insert(order);
        }
    }

    /**
     * 计算新创建的订单的缺失字段
     *
     * @param order
     */
    public void completeNewOrder(Order order) {
        order.setId(idGenerator.next());
        Product product = productRepository.findById(order.getProductId()).orElseThrow(() -> new JoymartBusinessException("错误的商品ID"));

        if (product.isDeleted() || product.isOnMarket() == false) {
            throw new JoymartBusinessException("商品已暂时停售");
        }
        if(order.getQuantity()<=0){
            throw new JoymartBusinessException("错误的数量");
        }

        //金额相关
        BigDecimal unitPrice = product.getPrice();
        BigDecimal unitPv = product.getPv();
        order.setUnitPrice(unitPrice);
        order.setUnitPv(unitPv);
        order.setTotalPrice(unitPrice.multiply(BigDecimal.valueOf(order.getQuantity()), MathContext.DECIMAL64));
        order.setTotalPv(unitPv.multiply(BigDecimal.valueOf(order.getQuantity()), MathContext.DECIMAL64));
        order.setFirstSellerProfit(order.getTotalPv().multiply(businessConfig.getPvCashRate()).multiply(businessConfig.getFirstSellerProfitRate(), MathContext.DECIMAL64));
        order.setSecondSellerProfit(order.getTotalPv().multiply(businessConfig.getPvCashRate()).multiply(businessConfig.getSecondSellerProfitRate(), MathContext.DECIMAL64));
        // 参与者相关
        String userId = (SecurityUtils.getCurrentUserId());
        CachedUser buyer = Optional.ofNullable(userCacheManager.get(userId)).orElseThrow();
        order.setBuyerId(userId);
        CachedUser firstSeller;
        if (buyer.getBusinessRoles().contains(BusinessRole.AG_SHOP)) { //店铺自购
            firstSeller = buyer;
        } else {
            firstSeller = Optional.ofNullable(userCacheManager.upwardSearchUntil(buyer, c -> c.getBusinessRoles().contains(BusinessRole.AG_SHOP))).orElseThrow();
        }
        order.setFirstSellerId(firstSeller.getUser().getId());
        CachedUser secondSeller = userCacheManager.upwardSearchUntil(firstSeller, c -> c.getBusinessRoles().contains(BusinessRole.AU_SHOP));
        if (secondSeller == null) { //初始金店铺的情况
            secondSeller = firstSeller;
        }
        order.setSecondSellerId(secondSeller.getUser().getId());

        order.setCreatedAt(DatetimeUtils.now());
    }

}
